const api = require('../../utils/api.js');
const app = getApp();
const order = require('../../utils/orders.js');
const utils = require('../../../ws_micro_shop/utils/utils.js');

let timer = null;
let cutTime = null;

Page({
  data: {
    again: true,
    order: null,
    getGoodsTotalPrice: function() {
      return this.data.order.total_price;
    },
    attachment_url: app.siteInfo.attachment_url,
    theme: app.themeData,
    unit: '',
    show: false,
    imgUrl: app.imgUrl,
    showpaytypes: false,
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    admin: '',
    isAdmin: false,
    hide: 1,
    qrcode: '',
  },
  onLoad(opts) {
    let options = opts || {};
    let isMulti =
      app.ws_micro_shop_globalData && app.ws_micro_shop_globalData.isMulti;
    app.pageOnLoad(this);
    let that = this;
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    that.setData({
      store: wx.getStorageSync('store'),
      commentSwitch: wx.getStorageSync('store').comment_switch,
      opts: options,
      isMulti,
      useTabbar: that.data.useTabbar && app.getTabBarStatus(),
      isAdmin: options.admin && options.admin == 'yes' ? true : false,
    });
    
  },
  onShow() {
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    this.getdetail();
  },
  getdetail() {
    let that = this;
    let { isMulti } = that.data;
    cutTime && clearInterval(cutTime);
    app.ws_micro_shoplogin().then(function () {
      app.ws_micro_shoprequest({
        url: api.order.detailNew,
        data: {
          order_id: that.data.opts.id,
        },
        success: function (res) {
          if (res.code === 0) {
            cutTime && clearInterval(cutTime);
            let this_data = res.data;
            let form_list = isMulti ? res.data.info[0].form_list : res.data.form_list;
            let leave_time = Number(res.data.timediff) || 0;

            function calc() {
              if (leave_time > 0) {
                leave_time--;
                that.setData({
                  leave_time: utils.getLeaveTime(leave_time),
                });
              } else {
                that.setData({
                  leave_time: 0,
                });
              }
            }
            cutTime = setInterval(function () {
              calc();
            }, 1000);

            for (let i in form_list) {
              if (Object.prototype.hasOwnProperty.call(form_list, i)) {
                let item = form_list[i];
                // 判断类型是否为上传图片,将value字符串拆分为数组
                if (item.type === 'uploadimg') {
                  let valueArr = item.value.split(',');
                  isMulti ? this_data.info[0].form_list[i].valueArr = valueArr : this_data.form_list[i].valueArr = valueArr;
                }
              }
            }
            // 门店内骑手配送订单不显示运费，订单金额都去掉运费（列表页、详情页） jane
            let pay_price = that.data.isAdmin && this_data.rider_id && Number(this_data.rider_id) > 0 ? parseFloat(this_data.pay_price) - parseFloat(this_data.info[0].express_price) : this_data.pay_price;
            that.setData({
              order: this_data,
              'order.o_type': 1,
              'order.pay_price': parseFloat(pay_price).toFixed(2),
            });
          }
        },
        complete: function () {
          wx.hideLoading();
        },
      });
    });
    app.loadShopSetting().then(res => {
      that.setData(res);
    });
  },
  onHide() {
    timer && clearInterval(timer);
    cutTime && clearInterval(cutTime);
  },
  onUnload() {
    timer && clearInterval(timer);
    cutTime && clearInterval(cutTime);
  },
  callsomeone(e) {
    let mobile = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: mobile,
    });
  },

  hide() {
    this.setData({
      hide: 1,
    });
  },

  copyText(e) {
    let text = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: text,
      success: function() {
        // wx.showToast({
        //   title: '已复制',
        //   icon: 'none',
        // });
      },
    });
  },

  location() {
    let page = this;
    let isMulti = page.data.isMulti;
    let shop = isMulti ? page.data.order.info[0].shop : page.data.order.shop;
    wx.openLocation({
      latitude: parseFloat(shop.latitude),
      longitude: parseFloat(shop.longitude),
      address: shop.address,
      name: shop.name,
    });
  },

  location2() {
    let page = this;
    let { lng, lat, address, name } = page.data.order;
    wx.openLocation({
      latitude: parseFloat(lat),
      longitude: parseFloat(lng),
      address: address,
      name: name,
    });
  },

  collectFormId(e) {
    app.collectFormId(e);
  },

  previewUpImage(e) {
    let that = this;
    let { isMulti, order } = that.data;
    let { url = '', index: idx = '' } = e.currentTarget.dataset;
    wx.previewImage({
      current: url,
      urls: isMulti ? order.info[0].form_list[idx].valueArr : order.form_list[idx].valueArr,
    });
  },

  bindTextAreaBlur(e) {
    this.setData({
      remarkTxt: e.detail.value,
    });
  },

  close() {
    this.setData({
      show: false,
    });
  },

  sendFinish() {
    this.setData({
      show: true,
    });
  },

  send() {
    let that = this;
    wx.showLoading({
      title: '正在提交',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.order.send_finish,
      data: {
        order_id: that.data.opts.id,
        words: that.data.remarkTxt,
      },
      success: function(res) {
        that.setData({
          show: false,
        });
        if (res.code === 0) {
          wx.showToast({
            title: '确认成功',
            duration: 1500,
            icon: 'success',
            success: function() {
              setTimeout(function() {
                that.setData({
                  'order.is_sender': 0,
                });
              }, 1500);
            },
          });
        }
        if (res.code === 1) {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
      complete: function() {
        wx.hideLoading();
      },
    });
  },
  quickAddCart(e) {
    order.quickAddCart(e);
  },
  orderPay(e) {
    order.orderPay(e, this.data.orderID, 1);
    this.setData({
      showpaytypes: false,
    });
  },

  orderRevoke(e) {
    let _this = this;
    let { id, msg, type, order_cancel } = e.currentTarget.dataset;
    order.orderRevoke(id, msg, type, order_cancel, res => {
      if (res.confirm) {
        wx.navigateBack({
          delta: 1,
        });
      }
    });
  },

  orderConfirm(e) {
    let _this = this;
    let { id, type } = e.currentTarget.dataset;
    order.orderConfirm(id, type, res => {
      if (res.code === 0) {
        _this.getdetail();
      }
    });
  },
  deleteOrder(e) {
    let that = this;
    let orderlist = that.data.order_list;
    order.deleteOrder(e, res => {
      if (res) {
        wx.navigateBack({
          delta: 1,
        });
      }
    });
  },
  orderQrcode(e) {
    let _this = this;
    let orderId = _this.data.order.order_id;
    let orderNo = _this.data.order.order_no;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    if (_this.data.order.offline_qrcode) {
      _this.setData({
        hide: 0,
        qrcode: _this.data.order.offline_qrcode,
      });
      wx.hideLoading();
    } else {
      order.orderQrcode(orderNo, orderId, 1, res => {
        if (res) {
          _this.setData({
            hide: 0,
            qrcode: res.data.url,
          });
          if (timer) {
            timer && clearInterval(timer);
          }
          _this.Loop(orderId);
        }
      });
    }
  },
  Loop(id) {
    let _this = this;
    timer = setInterval(function () {
      app.ws_micro_shoprequest({
        url: api.default.orderClerk,
        data: {
          order_id: id,
          type: 'default',
        },
        success: function (res) {
          if (res.code === 0) {
            if (Number(res.data) === 1) {
              timer && clearInterval(timer);
              _this.setData({
                hide: 1,
              });
              _this.loadOrderList(_this.data.status);
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.msg,
            });
          }
        },
      });
    }, 2000);
  },
  hidePayType() {
    this.setData({
      showpaytypes: false,
    });
  },
  showPayType(e) {
    this.getPayType(e);
  },
  getPayType(e) {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.order.pay_type,
      data: {
        order_id: e.currentTarget.dataset.id,
      },
      complete: function () {
        wx.hideLoading();
      },
      success: function (res) {
        if (res.code === 0) {
          that.setData({
            pay_type_list: res.data,
            showpaytypes: true,
            orderID: e.currentTarget.dataset.id,
            discountId:
              Number(e.currentTarget.dataset.discount) === 1
                ? e.currentTarget.dataset.payment
                : -1,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
    });
  },
  showMoreOpr(e) {
    this.setData({
      'order.showmorebtn': !this.data.order.showmorebtn,
    });
  },
  refund(e) {
    app.util.navigateTo('/ws_micro_shop/pages/order-refund/order-refund', {
      id: e.currentTarget.dataset.id,
      entry: 'default',
    });
  },
  ping(e) {
    order.ping(e);
  },
  customerTo() {
    let { card_openid, card_toopenid, card_id } = this.data;
    let url = '/common/component/universal-card/pages/message?openid=' + card_openid + '&to_openid=' + card_toopenid + '&cardid=' + card_id + '&scene=inner&m_id=0';
    app.util.navigateTo(url);
  },

  showExpressList(e) {
    let { orderid, iscycle } = e.currentTarget.dataset;
    let expresslist = this.data.order.express;
    if (Number(iscycle) === 1) {
      app.util.navigateTo(
        '/ws_micro_shop/pages/cycle-purchase/cycle-purchase',
        {
          order_id: orderid,
        }
      );
    } else {
      this.setData({
        expresslist,
        orderid,
        showexpress: expresslist.length > 0,
        express_id: '',
      });
    }
  },
  cancelCheck() {
    this.setData({
      showexpress: false,
      express_id: '',
    });
  },

  chooseExpressId(e) {
    this.setData({
      express_id: e.detail.value,
    });
  },

  sureCheck() {
    let { express_id, orderid } = this.data;
    if (!express_id) {
      wx.showToast({
        title: '请选择快递单号',
        icon: 'none',
      });
      return;
    }
    app.util.navigateTo('/ws_micro_shop/pages/express-detail/express-detail', {
      id: orderid,
      type: 'goods',
      express_id,
    });
  },
});
